package com.google.code.sapwcrawler.download.procedure;

import java.net.*;
import java.util.concurrent.TimeUnit;

public class DelayedDownloadProc extends DownloadProcDecorator
{
	private long delay = 0;
	private long lastTime = 0;
	public void setDelay(long v)
	{
		this.delay = v;
	}
	
	public void setDelay(TimeUnit tunit,long val)
	{
		setDelay(TimeUnit.MILLISECONDS.convert(val,tunit));
	}
	
	@Override
	public synchronized void download(URL url) throws IOException
	{
		waitTime();
		logTime();
		getDownloadProc().download(url);
	}
	
	private void waitTime() throws InterruptedException
	{
		long curr = System.currentTimeMillis();
		long expired_at = delay + lastTime;
		long diff = curr - expired_at;
		if(diff > 0)
			Thread.sleep(diff);
	}
	
	private void logTime()
	{
		this.lastTime = System.currentTimeMillis();
	}
}
